• File: customer_maintain_data_all.php
  • Full Path: C:/htdocs/REEFTintegrationLog_test/REEFTintegrationLog/x__saved/customer_maintain_data_all.php
  • Date Modified: 05/09/2025 7:34 AM
  • File size: 17.91 KB
  • MIME-type: text/x-php
  • Charset: utf-8
<?php

//======================================================================================
//
// Function: REEFTintegrationLog - Get customers
//
// Programmer: JKJ
// Date      : 2025-05-27
//
// ChatGPT Conversaion
// https://chatgpt.com/share/680e7c97-6c40-8012-83cd-aad9c3ba8ec3
//
// Copyright Reeft A/S (c) - 2025
//======================================================================================

//======================================================================================
// General config
//======================================================================================
	include "config/config.php";

//======================================================================================
// Set language
//======================================================================================

	include "include/set_language.php";

//======================================================================================
// Get input
//======================================================================================

	if (isset($_REQUEST["customer"])) {
		$customer = $_REQUEST["customer"];
	} else {
		$customer = '';
	}

	if (isset($_REQUEST["customer_type"])) {
		$customer_type = $_REQUEST["customer_type"];
	} else {
		$customer_type = '';
	}
	
	if (isset($_REQUEST["draw"])) {
		$draw = $_REQUEST["draw"];
	} else {
		$draw = 1;
	}

//======================================================================================
// Set database
//======================================================================================

	$db_name = 'customer/REEFT_integration.sqlite3';
	
//======================================================================================
// Start me up...
//======================================================================================
	$startTime = microtime(true);

//======================================================================================
// Check if database file exists
//======================================================================================
	if (!file_exists($db_name)) {
		die(json_encode(['error' => "Database file '$db_name' does not exist."]));
	}

//======================================================================================
// Connect to the database
//======================================================================================
	try {
		$db = new PDO('sqlite:' . $db_name);
		$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	} catch (PDOException $e) {
		die(json_encode(['error' => 'Database connection failed: ' . $e->getMessage()]));
	}

//======================================================================================
// Check if required table exists
//======================================================================================
	$tableCheck = $db->query("SELECT name FROM sqlite_master WHERE type='table' AND name='reeft_customer'");

	if ($tableCheck->fetchColumn() === false) {
		die(json_encode(['error' => "Table 'reeft_customer' does not exist in database '$db_name'."]));
	}

//======================================================================================
// Fetch all customer rows
//======================================================================================
	$data = [];
	$total_found = 0;
	$total_notfound = 0;

	// Set SQL and execute statement
	$query = "SELECT * FROM reeft_customer";
	$rows = $db->query($query)->fetchAll(PDO::FETCH_ASSOC);


	// Loop result
	foreach ($rows as $row) {
		
		// Count active/inactive
		if ((int)$row['cust_active'] === 1) {
			$total_found++;
		} else {
			$total_notfound++;
		}

		// Add useful fields
		$row['name'] 	= $row['cust_name'];
		$row['group'] 	= (int)$row['cust_group'];

		$data[] = $row;
		
	}

	$executionTime = microtime(true) - $startTime;

	// Build response
	$response = [
		'header' => [
			'db_name' => $db_name,		
			'total_found' => $total_found,
			'total_notfound' => $total_notfound,
			'total_total' => $total_found + $total_notfound,
			'execution_time_sec' => number_format($executionTime, 6),
			'execution_time_ms' => number_format($executionTime * 1000, 6)
		],
		'draw' => 1,
		'recordsTotal' => $total_found + $total_notfound,
		'recordsFiltered' => $total_found + $total_notfound,
		'data' => $data,
		'errors' => [] // placeholder
	];

	// Output as JSON
	header('Content-Type: application/json');
	echo json_encode($response, JSON_PRETTY_PRINT);


	exit;
	
	$db_name = 'customer/REEFT_integrationX.sqlite3';

$startTime = microtime(true);

try {
    $db = new PDO('sqlite:'.$db_name );
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die(json_encode(['error' => '...Database' . 'connection failed: ' . $e->getMessage()]));
}

$data = [];
$total_found = 0;
$total_notfound = 0;

// Get all customer rows
$query = "SELECT * FROM reeft_customer";
$rows = $db->query($query)->fetchAll(PDO::FETCH_ASSOC);

foreach ($rows as $row) {
    // Count active/inactive
    if ((int)$row['cust_active'] === 1) {
        $total_found++;
    } else {
        $total_notfound++;
    }

    // Add useful fields
    $row['name'] = $row['cust_name'];
    $row['group'] = (int) $row['cust_group'];

    $data[] = $row;
}

$executionTime = microtime(true) - $startTime;

// Build response
$response = [
    'header' => [
		'db_name' => $db_name,
        'total_found' => $total_found,
        'total_notfound' => $total_notfound,
        'total_total' => $total_found + $total_notfound,
        'execution_time_sec' => number_format($executionTime, 6),
        'execution_time_ms' => number_format($executionTime * 1000, 6)
    ],
    'draw' => 1,
    'recordsTotal' => $total_found + $total_notfound,
    'recordsFiltered' => $total_found + $total_notfound,
    'data' => $data,
    'errors' => [] // reserved
];

// Output as JSON
header('Content-Type: application/json');
echo json_encode($response, JSON_PRETTY_PRINT);
	
	
	exit;
	
	
$startTime = microtime(true);

try {
    $db = new PDO('sqlite:REEFT_integration.sqlite3');
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die(json_encode(['error' => 'Database connection failed: ' . $e->getMessage()]));
}

$data = [];
$errors = [];

$total_found = 0;

// You can add WHERE cust_active = 1 if needed
$query = "SELECT * FROM reeft_customer";
$rows = $db->query($query)->fetchAll(PDO::FETCH_ASSOC);

foreach ($rows as $row) {
    // Basic success wrapping
    $row['name'] = $row['cust_name'];
    $row['group'] = (int) $row['cust_group'];
    $row['json_filename'] = 'N/A'; // Placeholder
    $row['returnCode'] = '00';
    $row['returnMsg'] = 'Alles ist gut';

    $data[] = $row;
    $total_found++;
}

$executionTime = microtime(true) - $startTime;

// Final response
$response = [
    'header' => [
        'total_found' => $total_found,
        'total_notfound' => 0,
        'total_total' => $total_found,
        'execution_time_sec' => number_format($executionTime, 6),
        'execution_time_ms' => number_format($executionTime * 1000, 6)
    ],
    'draw' => 1,
    'recordsTotal' => $total_found,
    'recordsFiltered' => $total_found,
    'data' => $data,
    'errors' => [] // Placeholder if you ever need to validate rows
];

// Optional cache (commented)
// file_put_contents('cache.json', json_encode($response, JSON_PRETTY_PRINT));

header('Content-Type: application/json');
echo json_encode($response, JSON_PRETTY_PRINT);

	
	
	exit;

//======================================================================================

$startTime = microtime(true); // Start timing

$inputFile = 'data.txt';
$inputFile = 'customer/customer_conf.txt';
$data = [];
$errors = [];

$totalFound = 0;
$totalNotFound = 0;

if (file_exists($inputFile)) {
    $lines = file($inputFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

    foreach ($lines as $line) {
        list($filename, $someValue) = explode(';', $line, 2);

        $jsonFile = $filename . '.json';
		$jsonFile = 'customer/' . $filename . '.json';		
		
        $jsonData = [];
        $returnCode = '99';
        $returnMsg = 'File not found';

        if (file_exists($jsonFile)) {
            $jsonContent = file_get_contents($jsonFile);
            $decodedData = json_decode($jsonContent, true);

            if ($decodedData !== null) {
                $jsonData = $decodedData;
                $returnCode = '00';
                $returnMsg = 'Alles ist gut';
                $totalFound++;

                // Only add to data if file was found and valid
                $combined = array_merge([
                    'name' => $filename,
                    'group' => (int) $someValue,
                    'json_filename' => $jsonFile,
                    'returnCode' => $returnCode,
                    'returnMsg' => $returnMsg
                ], $jsonData);

                $data[] = $combined;
            } else {
                $totalNotFound++;
                $errors[] = [
                    'name' => $filename,
                    'json_filename' => $jsonFile,
                    'error' => 'Invalid JSON content'
                ];
            }
        } else {
            $totalNotFound++;
            $errors[] = [
                'name' => $filename,
                'json_filename' => $jsonFile,
                'error' => 'File not found'
            ];
        }
    }

    // Sort by group (value) and name
    usort($data, function($a, $b) {
        if ($a['group'] != $b['group']) {
            return $a['group'] <=> $b['group'];
        }
        return strcmp(strtolower($a['name']), strtolower($b['name']));
    });
}

$executionTimeSec = microtime(true) - $startTime;
$executionTimeMs = $executionTimeSec * 1000;

// --- Set cache headers (optional, can be commented out) ---
header('Content-Type: application/json');
// header('Cache-Control: public, max-age=30');
// header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 30) . ' GMT');

echo json_encode([
    'header' => [
        'total_found' => $totalFound,
        'total_notfound' => $totalNotFound,
        'total_total' => $totalFound + $totalNotFound,
        'execution_time_sec' => number_format($executionTimeSec, 6, '.', ''),
        'execution_time_ms' => number_format($executionTimeMs, 6, '.', '')
    ],
    'draw' => (int)$draw,
    'recordsTotal' => $totalFound,
    'recordsFiltered' => $totalFound,
    'data' => $data,
    'errors' => $errors
], JSON_PRETTY_PRINT);
	
	
	exit;
	
	
//======================================================================================	
	
	

$startTime = microtime(true); // Start timing

$inputFile = 'data.txt';
$inputFile = 'customer/customer_conf.txt';
$data = [];
$errors = [];

$totalFound = 0;
$totalNotFound = 0;

if (file_exists($inputFile)) {
    $lines = file($inputFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

    foreach ($lines as $line) {
        list($filename, $someValue) = explode(';', $line, 2);

        $jsonFile = $filename . '.json';
		$jsonFile = 'customer/' . $filename . '.json';

        $jsonData = [];
        $returnCode = '99';
        $returnMsg = 'File not found';

        if (file_exists($jsonFile)) {
            $jsonContent = file_get_contents($jsonFile);
            $decodedData = json_decode($jsonContent, true);

            if ($decodedData !== null) {
                $jsonData = $decodedData;
                $returnCode = '00';
                $returnMsg = 'Alles ist gut';
                $totalFound++;
            } else {
                $totalNotFound++;
                $errors[] = [
                    'name' => $filename,
                    'json_filename' => $jsonFile
                ];
            }
        } else {
            $totalNotFound++;
            $errors[] = [
                'name' => $filename,
                'json_filename' => $jsonFile
            ];
        }

        // Merge header and data into one object
        $combined = array_merge([
            'name' => $filename,
            'group' => (int) $someValue,
            'json_filename' => $jsonFile,
            'returnCode' => $returnCode,
            'returnMsg' => $returnMsg
        ], $jsonData);

        $data[] = $combined;
    }

    // Sort by group (value) and name
    usort($data, function($a, $b) {
        if ($a['group'] != $b['group']) {
            return $a['group'] <=> $b['group'];
        }
        return strcmp(strtolower($a['name']), strtolower($b['name']));
    });
}

$executionTimeSec = microtime(true) - $startTime;
$executionTimeMs = $executionTimeSec * 1000;

// --- Set cache headers (optional, can be commented out) ---
header('Content-Type: application/json');
// header('Cache-Control: public, max-age=30');
// header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 30) . ' GMT');

echo json_encode([
    'header' => [
        'total_found' => $totalFound,
        'total_notfound' => $totalNotFound,
        'total_total' => $totalFound + $totalNotFound,
        'execution_time_sec' => number_format($executionTimeSec, 6, '.', ''),
        'execution_time_ms' => number_format($executionTimeMs, 6, '.', '')
    ],
    'draw' => 1,
    'recordsTotal' => 180122,
    'recordsFiltered' => 180122,
    'data' => $data
], JSON_PRETTY_PRINT);



	exit;

//======================================================================================
// Set start time
//======================================================================================
	$startTime = microtime(true); // Start timing

//======================================================================================
// Set input file
//======================================================================================

	$inputFile = 'customer/customer_conf.txt';

//======================================================================================
// Init variables and arrays
//======================================================================================

	$output = [];
	$errors = [];

	$totalFound = 0;
	$totalNotFound = 0;

//======================================================================================
// Read the customer file
//======================================================================================

	if (file_exists($inputFile))
	{

		$lines = file($inputFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

		foreach ($lines as $line) {

			// Split the text line
			list($filename, $someValue) = explode(';', $line, 2);

			$jsonFile = $filename . '.json';
			$jsonFile = 'customer/' . $filename . '.json';

			// json file not found
			$data = [];
			$returnCode = '99';
			$returnMsg = 'File not found';

			// json file found
			if (file_exists($jsonFile)) {
				$jsonContent = file_get_contents($jsonFile);
				$jsonData = json_decode($jsonContent, true);

				if ($jsonData !== null) {
					$data = $jsonData;
					$returnCode = '00';
					$returnMsg = 'Alles ist gut';
					$totalFound++;
				} else {
					$totalNotFound++;
					$errors[] = [
						'name' => $filename,
						'json_filename' => $jsonFile
					];
				}
			} else {
				$totalNotFound++;
				$errors[] = [
					'name' => $filename,
					'json_filename' => $jsonFile
				];
			}

			$output[] = [
				'header' => [
					'name' => $filename,
					'group' => (int) $someValue,
					'json_filename' => $jsonFile,
					'returnCode' => $returnCode,
					'returnMsg' => $returnMsg
				],
				'data' => $data
			];
		}

//======================================================================================
// Sort by header.group first, then by header.name
//======================================================================================
		// usort($output, function($a, $b) {
			// return strcmp(strtolower($a['header']['group']), strtolower($b['header']['name']));
		// });

		usort($output, function($a, $b) {
			// Sort by group (ascending)
			if ($a['header']['group'] != $b['header']['group']) {
				return $a['header']['group'] <=> $b['header']['group'];
			}
			// If groups are the same, sort by name (ascending)
			return strcmp(strtolower($a['header']['name']), strtolower($b['header']['name']));
		});


	}

//======================================================================================
// Calculate execution time
//======================================================================================

	$executionTime 		= round((microtime(true) - $startTime) * 1000, 2); // in milliseconds
	$executionTime_sec 	= microtime(true) - $startTime; // seconds with 6 decimals

	$executionTimeSec = microtime(true) - $startTime;
	$executionTimeMs = $executionTimeSec * 1000;

//======================================================================================
// Set header and cache if wanted
//======================================================================================

	header('Content-Type: application/json');

	// --- Set cache headers (30 seconds) ---
	// header('Cache-Control: public, max-age=30'); // Browser can cache for 30 seconds
	// header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 30) . ' GMT');


//======================================================================================
// Return json, you naughty boy
//======================================================================================

	$pretty_print = '';


	echo json_encode([
		'result' => $output,
		'total' => [
			'dd_name' => $db_name,
			'total_found' => $totalFound,
			'total_notfound' => $totalNotFound,
			'total_total' => $totalFound + $totalNotFound,
			'execution_time_sec' => number_format($executionTimeSec, 6, '.', ''),
			'execution_time_ms' => number_format($executionTimeMs, 6, '.', '')
		],
		'errors' => $errors
	], JSON_PRETTY_PRINT);

?>